package com.pw.demo3.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pw.demo3.annotation.PerAnnotion;
import com.pw.demo3.bean.Department;
import com.pw.demo3.bean.Employee;
import com.pw.demo3.bean.EmployeeRole;
import com.pw.demo3.bean.Role;
import com.pw.demo3.service.impl.DepartmentServiceImpl;
import com.pw.demo3.service.impl.EmployeeRoleServiceImpl;
import com.pw.demo3.service.impl.EmployeeServiceImpl;
import com.pw.demo3.service.impl.RoleServiceImpl;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class employeeController {

    @Autowired
    EmployeeServiceImpl employeeService;

    @Autowired
    EmployeeRoleServiceImpl employeeRoleService;

    @Autowired
    DepartmentServiceImpl departmentService;

    @Autowired
    RoleServiceImpl roleService;

    @RequestMapping("/delete/{id}")
    @ResponseBody
    @PerAnnotion(name = "员工删除", expression = "employee:delete")
    public Map<String, Object> employeeDelete(@PathVariable String id) {
        Map<String, Object> map = new HashMap<>();
        try {
            employeeService.deleteByPrimaryKey(Long.valueOf(id));
            map.put("success", true);
        } catch (Exception e) {
            map.put("success", false);
            map.put("msg", "错误");
            e.printStackTrace();
        }
        return map;
    }

    @RequestMapping("/list")
    @PerAnnotion(name = "员工列表", expression = "employee:list")
    public String employeeList(Model model,
                               String currentPage,
                               HttpServletRequest request) {
        int pageNum = 1;
        if (currentPage != null) {
            pageNum = Integer.parseInt(currentPage);
        }
        PageHelper.startPage(pageNum, 5);
        List<Employee> employeeList;
        if (request.getParameter("dept") != null && request.getParameter("keyword") != null) {
            employeeList = employeeService.selectByExample(request.getParameter("keyword"), request.getParameter("dept"));
        } else {
            employeeList = employeeService.selectAll();
        }
        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);
        model.addAttribute("pageInfo", pageInfo);
        List<Department> departmentList = new ArrayList<>();
        for (Employee e : pageInfo.getList()) {
            departmentList.add(departmentService.selectByPrimaryKey(e.getDeptId()));
        }
        List<Department> departments = departmentService.selectAll();
        model.addAttribute("departmentList", departmentList);
        model.addAttribute("departments", departments);
        return "/views/employee/list";
    }

//    @RequestMapping("/select")
//    public String select(Model model, @RequestParam String key,
//                         @RequestParam String deptId,
//                         @RequestParam String currentPage) {
//        PageHelper.startPage(Integer.parseInt(currentPage), 5);
//        List<Employee> employeeList = employeeService.selectByKeyWord(key);
//        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);
//
//        model.addAttribute("pageInfo", pageInfo);
//        List<Department> departmentList = new ArrayList<>();
//        for (Employee e : pageInfo.getList()) {
//            departmentList.add(departmentService.selectByPrimaryKey(e.getDeptId()));
//        }
//        List<Department> departments = departmentService.selectAll();
//        model.addAttribute("departmentList", departmentList);
//        model.addAttribute("departments", departments);
//        return "/views/employee/list";
//    }

    @RequestMapping("/input")
    @PerAnnotion(name = "员工新增或者删除操作", expression = "employee:input")
    public String employeeInput(Model model,
                                @RequestParam(name = "id", defaultValue = "0") String id) {
        List<Department> departments = departmentService.selectAll();
        List<Role> roles = roleService.selectAll();
        Employee employee = employeeService.selectByPrimaryKey(Long.valueOf(id));
        model.addAttribute("departments", departments);
        model.addAttribute("roles", roles);
        model.addAttribute("employee", employee);
        if (!id.equals("0")) {
            List<EmployeeRole> employeeRoles = employeeRoleService.selectById(Long.valueOf(id));
            List<Role> selfRoles = new ArrayList<>();
            for (EmployeeRole e : employeeRoles) {
                selfRoles.add(roleService.selectByPrimaryKey(e.getRoleId()));
            }
            model.addAttribute("selfRoles", selfRoles);
        }
        return "views/employee/input";
    }

    @RequestMapping("/insert")
    public String insert(Model model,
                         Employee employee,
                         String repassword,
                         Long[] select2) {
        System.out.println("编辑用户");
        if (employee.getAdmin()==null){
            employee.setAdmin(false);
        }
        if (repassword == null) {
            update(employee, select2);
        } else {
            if (employee.getPassword().equals(repassword)) {
                //生成盐（部分，需要存入数据库中）
                ByteSource salt = ByteSource.Util.bytes("name");
                //将原始密码加盐（上面生成的盐），并且用md5算法加密1次，将最后结果存入数据库中
                String result = new Md5Hash(employee.getPassword(), salt, 1).toString();
                employee.setPassword(result);
                add(employee, select2);
            }
        }
        return "redirect:/employee/list";
    }

    private void update(Employee employee, Long[] select2) {
        Employee emp = employeeService.selectByPrimaryKey(employee.getId());
        emp.setName(employee.getName());
        emp.setEmail(employee.getEmail());
        emp.setDeptId(employee.getDeptId());
        emp.setAdmin(employee.getAdmin());
        emp.setAge(employee.getAge());
        try {
            employeeService.updateByPrimaryKey(emp);
            employeeRoleService.deleteById(emp.getId());
            addEmployeeRole(emp, select2);
        } catch (Exception e) {
            System.out.println("修改失败");
            e.printStackTrace();
        }
    }

    private void add(Employee employee, Long[] select2) {
        try {
            employeeService.insert(employee);
            addEmployeeRole(employee, select2);
        } catch (Exception e) {
            System.out.println("添加失败");
            e.printStackTrace();
        }
    }

    private void addEmployeeRole(Employee employee, Long[] select2) {
        for (Long s : select2) {
            EmployeeRole employeeRole = new EmployeeRole();
            employeeRole.setEmployeeId(employee.getId());
            employeeRole.setRoleId(s);
            employeeRoleService.insert(employeeRole);
        }
    }
}
